import 'package:flutter/material.dart';
import 'package:interesting_quiz/quiz/question.dart';
import 'package:interesting_quiz/quiz/quiz.dart';
import 'package:interesting_quiz/ui/answer_area.dart';
import 'package:interesting_quiz/ui/correct_wrong.dart';
import 'package:interesting_quiz/ui/question_area.dart';
import 'package:interesting_quiz/ui/score_page.dart';

class QuizPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new QuizPageState();
}

class QuizPageState extends State<QuizPage> {
  Quiz quiz = new Quiz([
    new Question('有‘文起八代之衰’美誉的是唐朝诗人：韩愈', true),
    new Question('地球自转一周是一月', false),
    new Question('维生素K通常可以由人体自行产生', true),
    new Question('科学的椅面高度应该等于人体身高的5分之1', false),
    new Question('现存地球上最大的哺乳动物是蓝鲸', true),
    new Question('人体最小的一块骨头是在脚上',  false),
    new Question('珊瑚是生物，而珊瑚虫不是生物', false),
    new Question('中国茶艺在宋代传入日本，形成日本茶道',  false),
    new Question('粤菜是中国八大菜系之首',  false),
    new Question('宫保鸡丁是中国的一道名菜，其中‘宫保’是指人名',  true),
  ]);
  Question currentQuestion;
  String questionName;
  int questionNum;
  bool isCorrect;
  bool isOverStack = false;

  @override
  void initState() {
    super.initState();
    currentQuestion = quiz.nextQuestion;
    questionName = currentQuestion.questionName;
    questionNum = quiz.questionNum;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      //这个stack里包含了一个问题、答案区域和一个展示答案是否正确的区域
      body: new Stack(
        fit: StackFit.expand, //将显示答案是否正确的控件充满整个屏幕
        children: <Widget>[
          new Column(
            children: <Widget>[
              new Expanded(
                  child: new AnswerArea(true, () => handleAnswer(true))),
              new QuestionArea(questionNum, questionName),
              new Expanded(
                  child: new AnswerArea(false, () => handleAnswer(false)))
            ],
          ),
          isOverStack == true
              ? CorrectOrWrong(
                  isCorrect,
                  () {
                    if (quiz.questionNum >= quiz.questionLength) {
                      Navigator.push(context,
                          new MaterialPageRoute(builder: (context) {
                        return new ScorePage(quiz.score, quiz);
                      }));
                    } else {
                      currentQuestion = quiz.nextQuestion;
                      setState(() {
                        isOverStack = false;
                        questionName = currentQuestion.questionName;
                        questionNum = quiz.questionNum;
                      });
                    }
                  },
                )
              : new Container(),
        ],
      ),
    );
  }

  void handleAnswer(bool answer) {
    if (currentQuestion.questionAnswer == answer) {
      isCorrect = true;
    } else {
      isCorrect = false;
    }
    quiz.answer(isCorrect);
    setState(() {
      isOverStack = true;
    });
  }
}
